package com.winchain.chainbill.asset.biz.credit.cmd;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.winchain.chainbill.chain.ChainCallbackService;
import com.winchain.chainbill.trade.service.TradeService;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillAssetTranCmd implements ICommand<AcctTxRec> {
	private Log logger = LogFactory.getLog(getClass());
	@Autowired
	private TradeService tradeService;
	@Autowired
	private ChainCallbackService chainCallbackService;

	public boolean execute(final CommandContext<AcctTxRec> context) throws Exception {
		final List<AcctTxRec> trans = (List) context.getValue("acctTxRecs");
		TransactionUtil.execute(new Transaction() {
			public void doInTransaction() {
				Map<String, String> result = BillAssetTranCmd.this.tradeService.fire(null, trans);
				context.setValue("txSnHost", result.get("tx_sn"));
			}
		}, new int[0]);

		final String txSnHost = (String) context.getValue("txSnHost");
		for (final AcctTxRec AcctTxRec : trans) {
			try {
				TransactionUtil.execute(new Transaction() {
					public void doInTransaction() {
						BillAssetTranCmd.this.chainCallbackService.callback(AcctTxRec, txSnHost);
					}
				}, new int[0]);
			} catch (Exception e) {
				e.printStackTrace();
				this.logger.error("chain callback error.");
			}
		}
		return false;
	}
}
